<template>
  <div class="about">
    <!-- <h1>This is an about page</h1> -->
    <!-- <h1>{{ text }}</h1> -->
    <div id="card">
      <div class="scrat">
        {{ text }}
        <canvas id="scratCan" class="scratcanvas"></canvas>
      </div>
    </div>
    <div>
      <button @click="reStart" style="float: left">再来一次</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
const text = ref("about myself");
const width = ref(400);
const height = ref(300);
function reStart() {
  // 重绘
  render();
}
function render() {
  let textObj = ["A赏", "B赏", "C赏", "D赏", "E赏", "F赏"];
  text.value = textObj[Math.floor(Math.random() * textObj.length)];
  // canvas 画板绘制图片
  // 创建div 设置内容
  let div = document.getElementById("card");
  // 创建 蒙版画布
  let canvas = document.getElementById("scratCan");
  // 设置 长 宽
  canvas.width = width.value;
  canvas.height = height.value;
  // 设置画笔
  const context = canvas.getContext("2d");
  // fillStyle 画笔填充
  context.fillStyle = "#efefef";
  context.fillRect(0, 0, width.value, height.value);
  // 再通过画笔绘制线条，之后通过线条和页面中重叠的地方进行消除，即可实现刮刮卡效果，将canvas添加到class叫scrat的div中。
  //画一个圆
  //画笔分割
  context.beginPath();
  //设置画笔的粗细
  context.lineWidth = 20;
  //转角和端点设置为圆弧
  context.lineCap = "round";
  context.lineJoin = "round";
  document.getElementsByClassName("scrat")[0].appendChild(canvas);
  // 添加点击移动事件，主要是监听用户鼠标三个事件，1、按下鼠标左键；2、移动鼠标；3、抬起鼠标左键。
  // 具体实现通过document.addEventListener来监听mousedown、mousemove、mouseup三种情况，修改鼠标状态isMouseDown的true和false来实现。
  //鼠标是否按下状态
  var isMouseDown = false;

  //鼠标按下，划线
  document.addEventListener("mousedown", function (event) {
    isMouseDown = true;
    //新旧图层重叠部分透明
    context.globalCompositeOperation = "destination-out";
    //封装函数，通过getCanvasPosition传入鼠标位置，获取在canvas中对应的位置
    var { x, y } = getCanvasPosition(event);
    //开始画线
    context.moveTo(x, y);
  });
  // 在这里可以对鼠标位置进行处理
  document.addEventListener("mousemove", function (event) {
    if (!isMouseDown) return;
    var { x, y } = getCanvasPosition(event);
    context.lineTo(x, y);
    context.stroke();
  });
  // eslint-disable-next-line no-unused-vars
  document.addEventListener("mouseup", function (event) {
    isMouseDown = false;
  });
  //封装函数。计算canvas位置
  function getCanvasPosition(event) {
    //获取鼠标当前位置
    var x = event.clientX;
    var y = event.clientY;
    //减去div的位置
    x -= div.offsetLeft;
    y -= div.offsetTop;

    //减去canvas的位置
    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;
    return { x, y };
  }
}
onMounted(() => {
  render();
});
</script>

<style>
.scrat {
  width: 400px;
  height: 300px;
  text-align: center;
  line-height: 300px;
  font-size: 64px;
  position: relative;
  border: 1px solid #000;
}
.scratcanvas {
  position: absolute;
  top: 0;
  left: 0;
  border: 1px solid #000;
}
</style>
